<template>
  <div>
    <!-- <span>{{' 路由传参:'+$store.state.indexType}}</span> -->
    <!-- 面包屑导航区域 也应该根据url动态渲染数据-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/market' }">沪深行情</el-breadcrumb-item>
      <el-breadcrumb-item>板块统计</el-breadcrumb-item>
      <el-breadcrumb-item v-if="$store.state.plateType==='industry'">行业板块</el-breadcrumb-item>
      <el-breadcrumb-item v-else-if="$store.state.plateType==='concept'">概念板块</el-breadcrumb-item>
      <el-breadcrumb-item v-else-if="$store.state.plateType==='area'">地域板块</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索区域 -->
      <el-breadcrumb separator-class=" ">
        <el-breadcrumb-item>  沪深指数：</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/plate/industry' }"><span :style="{'color':($store.state.plateType==='industry' ? 'orange':'')}">行业板块</span></el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/plate/concept' }"><span :style="{'color':($store.state.plateType==='concept' ? 'orange':'')}">概念板块</span></el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/plate/area' }"><span :style="{'color':($store.state.plateType==='area' ? 'orange':'')}">地域板块</span></el-breadcrumb-item>
        <el-breadcrumb-item></el-breadcrumb-item>
      </el-breadcrumb>
      <el-row :gutter="40">
        <el-col :span="10" style="marginLeft:10px;marginBottom:10px;">
          <el-input placeholder="请输入板块名称" v-model="queryInfo.selectPlateType" clearable @clear="getPlateType" v-show="showSelectInput">
            <el-button slot="append" icon="el-icon-search" @click="getPlateType"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
					  <el-button type="primary" @click="outPutPlate">导出Excel</el-button>

        </el-col>
      </el-row>

      <!-- 指数列表区域 -->
      <el-table id="plate" :data="plateData.list" stripe border resizable :default-sort="{prop: 'PERCENT', order: 'descending'}" :header-cell-style="{font:'12px Tahoma,san-serif',color:'#606266'}" width="550">
        <el-table-column label="排名" type="index" align="center"></el-table-column>
        <el-table-column label="板块名称" prop="NAME">
          <template slot-scope="scope">
            <!-- "https://money.163.com/+'{{code}}'+.html" -->
            <a href="#" target="__blank" class="hstock h_hstockName">
            {{scope.row.NAME}}
            </a>
          </template>
        </el-table-column>
        <el-table-column label="公司数" prop="STOCK_COUNT" width="70"></el-table-column>
        <el-table-column label="上涨" prop="UPNUM"></el-table-column>
        <el-table-column label="下跌" prop="DOWNNUM"></el-table-column>
        <el-table-column label="均价" prop="PRICE" sortable>
          <template slot-scope="scope">
            <span :style="{'color':((scope.row.PERCENT*100).toFixed(2)>0 ? 'red':'green')}">
              {{(scope.row.PRICE).toFixed(2)}}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="平均涨跌幅" prop="PERCENT" sortable width="120">
          <template slot-scope="scope">
            <span :style="{'color':((scope.row.PERCENT*100).toFixed(2)>0 ? 'red':'green')}">
              {{(scope.row.PERCENT * 100).toFixed(2) + '%'}}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="成交额(亿)" prop="TURNOVER" :formatter="handleYi" sortable  width="110"></el-table-column>
        <el-table-column label="成交量(万手)" prop="VOLUME" :formatter="handleWanShou"  width="100"></el-table-column>
        <!-- BUG：页面刚加载进行第一次请求可以正常渲染，可是当切换页面第二次请求时，后面对象数组里的调用总说为空 -->
        <!--    不使用插槽则没有问题，初步设想可能是和异步jsonp请求有关 -->
        <el-table-column label="领涨股" prop="MAXPERCENTSTOCK.NAME">
          <template slot-scope="scope">
            <a :href="'http://localhost:8080/#/market/'+scope.row.MINPERCENTSTOCK.CODE" target="__blank" class="hstock h_hstockName">
            {{scope.row.MAXPERCENTSTOCK.NAME}}
            </a>
          </template>
        </el-table-column>
        <el-table-column label="现价" prop="MAXPERCENTSTOCK">
          <template slot-scope="scope">
            <span style="color:red">
              {{(scope.row.MAXPERCENTSTOCK.PRICE).toFixed(2)}}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="涨幅" prop="MAXPERCENTSTOCK">
          <template slot-scope="scope">
            <span style="color:red">
              {{((scope.row.MAXPERCENTSTOCK.PERCENT) * 100 ).toFixed(2)+ '%'}}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="领跌股" prop="MINPERCENTSTOCK">
          <template slot-scope="scope">
            <a :href="'http://localhost:8080/#/market/'+scope.row.MINPERCENTSTOCK.CODE" target="__blank" class="hstock h_hstockName">
            {{scope.row.MINPERCENTSTOCK.NAME}}
            </a>
          </template>
        </el-table-column>
        <el-table-column label="现价" prop="MINPERCENTSTOCK">
          <template slot-scope="scope">
            <span style="color:green">
              {{(scope.row.MINPERCENTSTOCK.PRICE).toFixed(2)}}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="跌幅" prop="MINPERCENTSTOCK">
          <template slot-scope="scope">
            <span style="color:green">
              {{((scope.row.MINPERCENTSTOCK.PERCENT) * 100 ).toFixed(2)+ '%'}}
            </span>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination @size-change="handleCountChange" @current-change="handleCurrentChange" :current-page="queryInfo.page" :page-sizes="queryInfo.sizesOption()" :page-size="queryInfo.count" layout="total, sizes, prev, pager, next, jumper" :total="plateData.total">
      </el-pagination>
    </el-card>
  </div>
      
</template>

<script>
export default {
  data() {
    return {
      showSelectInput:true,
      plateData:[],
      url:'',
      // http://quotes.money.163.com/hs/realtimedata/service/plate.php?host=/hs/realtimedata/service/plate.php&page=0&query=TYPE:HANGYE&fields=RN,NAME,STOCK_COUNT,PE,LB,HSL,PERCENT,TURNOVER,VOLUME,PLATE_ID,TYPE_CODE,PRICE,UPNUM,DOWNNUM,MAXPERCENTSTOCK,MINPERCENTSTOCK&sort=PERCENT&order=desc&count=25&type=query

      queryInfo:{
        industryQuery:'TYPE:HANGYE',
        conceptQuery:'TYPE:GAINIAN',
        areaQuery:'TYPE:DIYU',
        selectPlateName:'',
        selectIndexQuery:'',
        sizesOption:function () {
          var arr = new Array()
          for(var i=1;i<=5;i++){
            arr.push(i*5)
          }
          return arr
        },
        page:1,
        count:10
      },
      total:0,
      plateURL:'',
      industryURL:'',
      conceptURL:'',
      areaURL:'',
    }
  },
  methods: {
    getPlateTypeURL(){
      // 请求地址中的当前页是从0开始的，因为handleCurrentChange方法中的页码也是从1开始计算的，为了保持一致就将data中的page定义为1，所以参数中需要this.queryInfo.page-1
      if (this.$store.state.plateType==='industry') {
        this.industryURL='http://quotes.money.163.com/hs/realtimedata/service/plate.php?host=/hs/realtimedata/service/plate.php&page='+(this.queryInfo.page-1)+'&query='+this.queryInfo.industryQuery+'&fields=RN,NAME,STOCK_COUNT,PE,LB,HSL,PERCENT,TURNOVER,VOLUME,PLATE_ID,TYPE_CODE,PRICE,UPNUM,DOWNNUM,MAXPERCENTSTOCK,MINPERCENTSTOCK&sort=PERCENT&order=desc&count='+this.queryInfo.count+'&type=query';
        this.plateURL = this.industryURL
        console.log(this.plateURL);
      }else if(this.$store.state.plateType==='concept'){
        // 搜索区域
        if(((this.queryInfo.selectPlateName).trim()).length !== 0){
          // 不能直接改变Query，这样会造成搜索一次之后Query已经发生改变，再清空input想查询所有的依旧查询不到
          this.queryInfo.selectPlateName='NAME:'+this.queryInfo.selectPlateName+';TYPE:HANGYE'
          console.log(this.queryInfo.selectPlateName);
          // page和count也要改变，否则当不在第一页时，page和count会有所改变，从而与网易财经的请求地址不符，请求不到数据
          // this.hushiIndexURL='http://quotes.money.163.com/hs/service/hsindexrank.php?host=/hs/service/hsindexrank.php&page=0&query='+this.queryInfo.selectIndexQuery+'&fields=no,SYMBOL,NAME,PRICE,UPDOWN,PERCENT,zhenfu,VOLUME,TURNOVER,YESTCLOSE,OPEN,HIGH,LOW&sort=SYMBOL&order=asc&count=25&type=query';
          console.log(this.industryURL);
        }else{
          // 未搜索
          this.conceptURL='http://quotes.money.163.com/hs/realtimedata/service/plate.php?host=/hs/realtimedata/service/plate.php&page='+(this.queryInfo.page-1)+'&query='+this.queryInfo.conceptQuery+'&fields=RN,NAME,STOCK_COUNT,PE,LB,HSL,PERCENT,TURNOVER,VOLUME,PLATE_ID,TYPE_CODE,PRICE,UPNUM,DOWNNUM,MAXPERCENTSTOCK,MINPERCENTSTOCK&sort=PERCENT&order=desc&count='+this.queryInfo.count+'&type=query';

        }
        this.plateURL = this.conceptURL
        console.log(this.plateURL);
      }else if(this.$store.state.plateType==='area'){
        // 搜索区域
        if(((this.queryInfo.selectPlateName).trim()).length !== 0){
          /* this.queryInfo.selectIndexQuery='SYMBOL:'+this.queryInfo.selectIndexSymbol+';IS_INDEX:true;EXCHANGE:CNSESZ'
          console.log(this.queryInfo.selectIndexQuery);
          this.shenshiIndexURL='http://quotes.money.163.com/hs/service/hsindexrank.php?host=/hs/service/hsindexrank.php&page=0&query='+this.queryInfo.selectIndexQuery+'&fields=no,SYMBOL,NAME,PRICE,UPDOWN,PERCENT,zhenfu,VOLUME,TURNOVER,YESTCLOSE,OPEN,HIGH,LOW&sort=SYMBOL&order=asc&count=25&type=query';
          console.log(this.hushiIndexURL); */
        }else{
          // 未搜索
          this.areaURL='http://quotes.money.163.com/hs/realtimedata/service/plate.php?host=/hs/realtimedata/service/plate.php&page='+(this.queryInfo.page-1)+'&query='+this.queryInfo.areaQuery+'&fields=RN,NAME,STOCK_COUNT,PE,LB,HSL,PERCENT,TURNOVER,VOLUME,PLATE_ID,TYPE_CODE,PRICE,UPNUM,DOWNNUM,MAXPERCENTSTOCK,MINPERCENTSTOCK&sort=PERCENT&order=desc&count='+this.queryInfo.count+'&type=query';
        }
        this.plateURL = this.areaURL
        console.log(this.plateURL);
      }
    },
    getPlateType(){
      // 此处将由于是请求的网易财经数据，将参数写进地址了，如果不这样，浏览器存在跨域问题Cross-Origin，需要设置CORB，在实际项目中调用后台接口应该传入参数，
      /* if (this.$store.state.indexType==='main') {
        url = this.mainIndexURL
      } */
      // this.$jsonp(this.url,{param:this.mainIndexParams},(err,res)=>{
      this.getPlateTypeURL();
      this.$jsonp(this.plateURL,(err,res)=>{
        if(!err){
          console.log(res);
          this.plateData=res;
        }
      });
    },
    // 监听count改变的事件
    handleCountChange(newCount) {
      console.log(newCount)
      this.queryInfo.count = newCount
      this.getPlateType()
      // 点击分页，让页面回到顶部
      if(document.body.scrollTop){
        document.body.scroll(Top)
      }else{
        document.documentElement.scrollTop=0
      }
    },
    // 监听 页码值 改变的事件
    handleCurrentChange(newPage) {
      console.log(newPage)
      this.queryInfo.page = newPage
      this.getPlateType()
      if(document.body.scrollTop){
        document.body.scroll(Top)
      }else{
        document.documentElement.scrollTop=0
      }
    },
    handleFix:function(row,column){
      return (row[(column).property]).toFixed(2)
    },
    handlePercent:function(row,column){
      return ((row[column.property])*100).toFixed(2)+'%'
    },
    handleYi:function(row,column){
      return ((row[column.property]) / 100000000).toFixed(2)
    },
    handleWanShou:function(row,column){
      return ((row[column.property]) / 1000000).toFixed(2)
    },
    outPutPlate() {
      /* generate workbook object from table */
      var wb = XLSX.utils.table_to_book(document.querySelector("#plate"));//mytable为表格的id名
      /* get binary string as output */
      var wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array"
      });
      try {
        FileSaver.saveAs(
          new Blob([wbout], { type: "application/octet-stream" }),
          "sheet.xlsx"
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    }
  },
  // 利用计算属性监听vuex中的数据变化，当url参数变化时，在page组件中一旦url变化，立即改变vuex中的indexType
  // 在该组件中一旦vuex变化，立即调用方法，让数据也随之发生变化，因为获取数据是在created中，一旦页面加载完成不会再调用方法
  // 而该页面使用的是路由跳转，如果不监听url变化重新渲染数据，会停留在前一路由中
  computed:{
    watchURLChange(){
      return this.$store.state.plateType
    }
  },
  watch:{
    // (监听hsIndexData也可以成功跳转，但是BUG：会一致监听不会断开！！！因为一旦数据变化会调用方法，又会再次获取新数据，数据变化又会重新调用，监听断不开造成死循环）
    watchURLChange(){
      console.log('页面跳转');
      // 路由跳转这些参数全部需要重新设置一下，因为是共用data中的数据，一个页面在调用后如果不重新设置，改变后的数据会影响下一个页面
      // 搜索框的显示与隐藏
      this.showSelectInput=true
      // 请求参数
      this.queryInfo.selectPlate = ''
      this.queryInfo.page=1
      this.queryInfo.count=10
      this.total=0
      // 一旦参数变化，立即重新发送请求更新页面数据
      this.getPlateType()
    }
  },
  created() {
    _plate.getPlateType()
    var _plate=this;
    // setInterval不会清除定时器队列，每重复执行1次都会导致定时器叠加，最终卡死网页。
    // 但是setTimeout是自带清除定时器的
    window.setInterval(() => {
      setTimeout(_plate.getPlateType(), 0)
    }, 30000)
    console.log('***************************PlateOVER******************************');
  }
}
</script>